package com.huaiwei.usmManager.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaiwei.usmManager.common.exception.RRException;
import com.huaiwei.usmManager.common.utils.PageUtils;
import com.huaiwei.usmManager.common.utils.Query;
import com.huaiwei.usmManager.modules.sys.service.SysUserService;
import com.huaiwei.usmManager.modules.sys.dao.SysUserDao;
import com.huaiwei.usmManager.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;


/**
 * 系统用户
 *
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

	@Override
	public SysUserEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}


	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}

	@Override
	public PageUtils getPageList(Map<String, Object> params) {
		/*获取要查询的条件*/
		String username= (String) params.get("username");
		String nickname= (String) params.get("nickname");
		IPage<SysUserEntity> page=this.page(new Query<SysUserEntity>().getPage(params),
				new QueryWrapper<SysUserEntity>().
						eq(StringUtils.isNotBlank(username),"username",username).
						like(StringUtils.isNotBlank(nickname),"nickname",nickname));
		return new PageUtils(page);
	}

	@Override
	public void insertOrUpdate(SysUserEntity userEntity) {
		if(userEntity.getUserId()==null){
			if(queryByUserName(userEntity.getUsername())!=null){
				throw new RRException("用户名已存在！");
			}
			userEntity.setCreateTime(new Date());
			/*计算盐值*/
			String salt= RandomStringUtils.randomAlphanumeric(20);
			/*密码加密*/
			String saltPassword=new Sha256Hash(userEntity.getPassword(),salt).toHex();
			userEntity.setPassword(saltPassword);
			userEntity.setSalt(salt);
			if(StringUtils.isBlank(userEntity.getAvatar())){
				userEntity.setAvatar("avatar.png");
			}
			this.save(userEntity);
		}else{
			this.updateById(userEntity);
		}
	}

}
